<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\command\logic\BaseLogic;
use think\console\Output;

/**
 * 统计-商家-会员数据
 * php think cli stats_shop_member --msg='{"days":30}'
 */
class CliStatsShopMemberLogic extends BaseLogic implements CliInterface
{

    /**
     * 入口方法
     * {@inheritdoc}
     */
    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            self::dataForMember($date);
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                self::dataForMember($date);
            }
        }
        return true;
    }

    private static function dataForMember($date)
    {
        $end = $date . ' 23:59:59';

        // status 0待支付 1待发货 2待收款 3已收货 4已完成 5退款中 6团款成功
        $field = [
            'shop_id',
            'user_id',
            'count(*) order_count',
            'sum(CASE WHEN pay_at is null THEN 0 ELSE 1 END) AS pay_order_count',
            'sum(CASE WHEN pay_at is null THEN 0 ELSE pay_price END) AS pay_price', //
        ];
        $rows = \think\facade\Db::table('order_shop')
            ->field($field)
            ->where('deleted', 0)
            ->whereBetweenTime('create_at', $date, $end)
            ->group('shop_id, user_id')
            ->select()->toArray();
        if (empty($rows)) {
            return true;
        }
        // echo \think\facade\Db::table('order_shop')->getlastsql();
        // var_dump($rows);exit;
        // `amount` int(11) DEFAULT '0' COMMENT '会员总数',
        // `view_count` int(11) DEFAULT '0' COMMENT '访问人数',
        // `new_count` int(11) DEFAULT '0' COMMENT '新增加会员数',
        $user_ids = array_column($rows, 'user_id');
        $userMap  = \think\facade\Db::table('member')
            ->whereIn('id', $user_ids)
            ->column(['id', 'level', 'user_name'], 'id');
        // var_dump($userMap);exit;

        $insertData = [];
        foreach ($rows as $row) {
            $user              = $userMap[$row['user_id']] ?? [];
            $row['date']       = $date;
            $row['user_level'] = $user['level'] ?? 0;
            $row['user_name']  = $user['user_name'] ?? '';
            $insertData[]      = $row;
        }
        \think\facade\Db::table('stats_shop_member')
            ->replace()
            ->insertAll($insertData);
        return true;
    }
}
